#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_libxml2_fun_001.py
@Time:      2024/02/22 11:12:50
@Author:    hongfeng
@Version:   1.0
@Contact:   wb-zhf668260@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    hongfeng
"""

from common.basetest import LocalTest
class Test(LocalTest):
    """
    See tc_libxml2_fun_001.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "libxml2-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > create_xml.c <<EOF
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

int main() {
    xmlDocPtr doc = NULL;
    xmlNodePtr root_node = NULL, child_node = NULL;

    // 初始化libxml2
    xmlInitParser();

    // 创建一个新的XML文档
    doc = xmlNewDoc(BAD_CAST "1.0");
    if (doc == NULL) {
        fprintf(stderr, "Error creating document\\n");
        return 1;
    }

    // 创建根节点
    root_node = xmlNewNode(NULL, BAD_CAST "root");
    if (root_node == NULL) {
        fprintf(stderr, "Error creating root node\\n");
        xmlFreeDoc(doc);
        return 1;
    }

    // 将根节点添加到文档中
    xmlDocSetRootElement(doc, root_node);

    // 在根节点下创建子节点
    child_node = xmlNewChild(root_node, NULL, BAD_CAST "child", BAD_CAST "Hello, World!");
    if (child_node == NULL) {
        fprintf(stderr, "Error creating child node\\n");
        xmlFreeDoc(doc);
        return 1;
    }

    // 保存XML文档到文件
    int result = xmlSaveFormatFileEnc("created.xml", doc, "UTF-8", 1);
    if (result < 0) {
        fprintf(stderr, "Error saving XML to file\\n");
    }

    // 清理并释放资源
    xmlFreeDoc(doc);
    xmlCleanupParser();

    return 0;
}
"""
        self.cmd(cmdline)
        self.cmd("gcc -o create_xml create_xml.c `xml2-config --cflags --libs`")

    def test(self):
        self.cmd("./create_xml")
        ret_c,ret_o = self.cmd("cat created.xml")
        self.assertTrue('<?xml version="1.0" encoding="UTF-8"?>' in ret_o, 'check output error.')
        self.assertTrue("<root>" in ret_o, 'check output error.')
        self.assertTrue("<child>Hello, World!</child>" in ret_o, 'check output error.')
        self.assertTrue("</root>" in ret_o, 'check output error.')
        
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm create_xml.c create_xml created.xml")
